package com.keydom.ropeskipping;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.keydom.ropeskipping.dot.CardHomeworkResultDTO;
import com.keydom.ropeskipping.dot.SkipDataDTO;
import com.keydom.ropeskipping.dot.StudentHomeworkDTO;
import com.keydom.ropeskipping.service.SkipWorkServiceImpl;
import com.keydom.ropeskipping.utils.HttpRequestUtil;
import com.keydom.ropeskipping.view.Circleprogressbar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class WorkActivity extends Activity {
    private String TAG = "WorkActivity";

    private TextView textBle;
    private TextView textTitle;
    private TextView textPower;
    private TextView textTime;
    private TextView textCount;
    private TextView textView;
    private TextView textHint;
    private TextView startButton;
    private LinearLayout startButtonLayout;
    private ImageView image1;
    private ImageView image2;
    private ImageView imageBleDown;
    private LinearLayout layoutBleSwitch;
    private LinearLayout linearLayout1;
    private LinearLayout linearLayout2;
    private LinearLayout layoutResult;
    private TextView textResult;
    private ImageView imageResult;
    private Circleprogressbar circleProgressbar1;
    private Circleprogressbar circleProgressbar2;

    private StudentHomeworkDTO studentHomeworkDTO;
    private BleDevice bleDevice = null;
    private String bleResult;

    private String targetApdu = "";
    private String typeApdu;
    private String startApdu;
    private Timer powerTimer;
    private TimerTask powerTimerTask;
    private Timer timeTimer;
    private TimerTask timeTimerTask;
    //绿色
    private int[] arcColors1 = {0xFF0BB485, 0xFF0BB485, 0xFF55EEC3, 0xFF0CBE8C, 0xFF0BB485, 0xFF01F5B1, 0xFF0BB485,};
    //黄色
    private int[] arcColors2 = {0xFFDF7256, 0xFFDF7256, 0xFFFA9D73, 0xFFF0815B, 0xFFF0815B, 0xFFFA9D73, 0xFFDF7256};

    /**
     * 通过个数上报是否从1开始判断跳绳上报是否有效
     */
    private boolean isEffective = false;
    private int sportCount = 0;
    private int sportTime = 0;
    private long startTime;
    /**
     * 作业是否结束
     */
    private boolean isCompleted = false;

    private Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    stopTime();
                    if (powerTimer != null) {
                        powerTimer.cancel();
                    }
                    if (powerTimerTask != null) {
                        powerTimerTask.cancel();
                    }
                    powerTimer = null;
                    powerTimerTask = null;
                    handler.removeMessages(0);
                    BleManager.getInstance().stopNotify(bleDevice, BleManager.getInstance().NOTIFY_SERVICE_UUID, BleManager.getInstance().NOTIFY_UUID);
                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(0x80000000);
        setContentView(R.layout.activity_work);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        AppApplication.getInstance().addActivity(this);

        studentHomeworkDTO = (StudentHomeworkDTO) getIntent().getSerializableExtra("data");
        initView();
        initEvent();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        textBle = findViewById(R.id.text_ble);
        textTitle = findViewById(R.id.textTitle);
        textPower = findViewById(R.id.text_power);
        textTime = findViewById(R.id.text_time);
        textCount = findViewById(R.id.text_count);
        textView = findViewById(R.id.text_view);
        textHint = findViewById(R.id.text_hint);
        startButton = findViewById(R.id.startButton);
        startButtonLayout = findViewById(R.id.startButtonLayout);
        image1 = findViewById(R.id.image1);
        image2 = findViewById(R.id.image2);
        imageBleDown = findViewById(R.id.image_ble_down);
        layoutBleSwitch = findViewById(R.id.layout_ble_switch);
        linearLayout1 = findViewById(R.id.linearLayout1);
        linearLayout2 = findViewById(R.id.linearLayout2);
        circleProgressbar1 = findViewById(R.id.circleProgressBar1);
        circleProgressbar2 = findViewById(R.id.circleProgressBar2);
        layoutResult = findViewById(R.id.layoutResult);
        textResult = findViewById(R.id.textResult);
        imageResult = findViewById(R.id.imageResult);

        if (BleManager.getInstance().getAllConnectedDevice().size() > 0) {
            bleDevice = BleManager.getInstance().getAllConnectedDevice().get(0);
        }

        if (studentHomeworkDTO.getType() == 0) {
            //计时计数
            textTitle.setText("计时计数作业");
            textHint.setText("目标时间   目标个数");
            textTime.setText(convertSecondsToMinutesSeconds(studentHomeworkDTO.getSportSeconds()));
            textCount.setText(String.valueOf(studentHomeworkDTO.getSportCount()));
            circleProgressbar1.setMaxprogress(studentHomeworkDTO.getSportCount());
            circleProgressbar1.setBorderColor(0x5010D59E);
            circleProgressbar1.setPathColor(0x5010D59E);
            circleProgressbar1.setArcColors(arcColors1);
            circleProgressbar2.setMaxprogress(studentHomeworkDTO.getSportSeconds());
            circleProgressbar2.setBorderColor(0x50F7976F);
            circleProgressbar2.setPathColor(0x50F7976F);
            circleProgressbar2.setArcColors(arcColors2);
            typeApdu = "*{\"an\":\"sm\",\"mo\":\"fr\"}#";
            startApdu = "*{\"an\":\"st\",\"mo\":\"fr\"}#";
        } else if (studentHomeworkDTO.getType() == 1) {
            //计时
            textTitle.setText("计时作业");
            textHint.setText("目标时间");
            textTime.setText(convertSecondsToMinutesSeconds(studentHomeworkDTO.getSportSeconds()));
            textView.setText("");
            circleProgressbar2.setVisibility(View.GONE);
            image2.setVisibility(View.GONE);
            linearLayout2.setVisibility(View.GONE);
            linearLayout1.setBackgroundResource(R.drawable.shape_orange);
            image1.setImageResource(R.mipmap.head);
            circleProgressbar1.setMaxprogress(studentHomeworkDTO.getSportSeconds());
            circleProgressbar1.setBorderColor(0x50F7976F);
            circleProgressbar1.setPathColor(0x50F7976F);
            circleProgressbar1.setArcColors(arcColors2);
            targetApdu = "*{\"an\":\"ti\",\"t\":\"" + studentHomeworkDTO.getSportSeconds() + "\"}#";
            typeApdu = "*{\"an\":\"sm\",\"mo\":\"ti\"}#";
            startApdu = "*{\"an\":\"st\",\"mo\":\"ti\"}#";
        } else {
            //计数
            textTitle.setText("计数作业");
            textHint.setText("目标个数");
            textCount.setText(String.valueOf(studentHomeworkDTO.getSportCount()));
            textView.setText("");
            circleProgressbar2.setVisibility(View.GONE);
            image2.setVisibility(View.GONE);
            linearLayout2.setVisibility(View.GONE);
            linearLayout1.setBackgroundResource(R.drawable.shape_orange);
            image1.setImageResource(R.mipmap.head);
            circleProgressbar1.setMaxprogress(studentHomeworkDTO.getSportCount());
            circleProgressbar1.setBorderColor(0x50F7976F);
            circleProgressbar1.setPathColor(0x50F7976F);
            circleProgressbar1.setArcColors(arcColors2);
            targetApdu = "*{\"an\":\"co\",\"c\":\"" + studentHomeworkDTO.getSportCount() + "\"}#";
            typeApdu = "*{\"an\":\"sm\",\"mo\":\"co\"}#";
            startApdu = "*{\"an\":\"st\",\"mo\":\"co\"}#";
        }
        //停止跳绳
        BleManager.getInstance().write(bleDevice, "*{\"an\":\"sp\",\"nu\":\"0\",\"t\":\"0\"}#");

        //每分钟更新一次电量
        powerTimer = new Timer();
        powerTimerTask = new TimerTask() {
            @Override
            public void run() {
                BleManager.getInstance().write(bleDevice, "*{\"an\":\"ba\"}#");
            }
        };
        powerTimer.schedule(powerTimerTask, 1500, 60000);

        IntentFilter filter = new IntentFilter();
        filter.addAction("DIS_CONNECT_BLE");
        registerReceiver(mBroadcastReceiver, filter);
    }

    private void initEvent() {
        findViewById(R.id.title_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                BleManager.getInstance().notify(
                    bleDevice,
                    BleManager.getInstance().NOTIFY_SERVICE_UUID,
                    BleManager.getInstance().NOTIFY_UUID,
                    new BleNotifyCallback() {
                        @Override
                        public void onNotifySuccess() {
                            // 打开通知操作成功
                            Log.e(TAG, "打开通知操作成功");
                        }

                        @Override
                        public void onNotifyFailure(BleException exception) {
                            // 打开通知操作失败
                            Log.e(TAG, "打开通知操作失败");
                        }

                        @SuppressLint("SetTextI18n")
                        @Override
                        public void onCharacteristicChanged(byte[] data) {
                            // 打开通知后，设备发过来的数据将在这里出现
                            String result = HexUtil.hexToString(HexUtil.encodeHexStr(data));
                            if (result.startsWith("*")) {
                                bleResult = "";
                            }
                            bleResult += result;
                            Log.e(TAG, "接收分包数据" + bleResult);
                            if (bleResult.startsWith("*") && bleResult.endsWith("#")) {
                                Log.e(TAG, "接收到数据" + bleResult);
                                bleResult = bleResult.replace("*", "").replace("#", "");
                                Map<String, Object> map = HttpRequestUtil.jsonToMap(bleResult);
                                if (map != null && map.containsKey("an")) {
                                    switch (map.get("an").toString()) {
                                        case "ba":
                                            //接收到电量消息
                                            int power = Integer.parseInt(map.get("nu").toString(), 16);
                                            if (power >= 4100) {
                                                //100%电
                                                textPower.setTextColor(Color.parseColor("#AFA6DA"));
                                                textPower.setText("电量：100%");
                                            } else if (power <= 3100) {
                                                //0%电
                                                textPower.setTextColor(Color.parseColor("#EB7C62"));
                                                textPower.setText("电量：0%");
                                            } else {
                                                int nowPower = (power - 3100) / 10;
                                                if (nowPower <= 20) {
                                                    textPower.setTextColor(Color.parseColor("#EB7C62"));
                                                } else {
                                                    textPower.setTextColor(Color.parseColor("#AFA6DA"));
                                                }
                                                textPower.setText("电量：" + nowPower + "%");
                                            }
                                            break;
                                        case "sd":
                                            //接收到离线数据上报
                                            BleManager.getInstance().write(bleDevice, "*{\"an\":\"ud\"}#");
                                            List<SkipDataDTO> dataDTOS = new ArrayList<>();
                                            try {
                                                JSONArray jsonArray = (JSONArray) map.get("da");
                                                for (int i = 0; i < jsonArray.length(); i++) {
                                                    JSONObject item = (JSONObject) jsonArray.get(i);
                                                    SkipDataDTO skipDataDTO = new SkipDataDTO();
                                                    long startTime = Integer.parseInt(item.get("st").toString(), 16) * 1000L;
                                                    long endTime = Integer.parseInt(item.get("et").toString(), 16) * 1000L;
                                                    skipDataDTO.setBeginTime(startTime);
                                                    skipDataDTO.setCompleteTime(endTime);
                                                    skipDataDTO.setSportNum(Integer.parseInt(item.get("nu").toString(), 16));
                                                    skipDataDTO.setSportTime((int) ((endTime - startTime) / 1000));
                                                    dataDTOS.add(skipDataDTO);
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            uploadHistoryWork(dataDTOS);
                                            break;
                                        case "gn":
                                            //个数变化上报
                                            if (isCompleted) {
                                                return;
                                            }
                                            int count = Integer.parseInt(map.get("nu").toString(), 16);
                                            if (count == 1) {
                                                if (sportCount != 0 && count < sportCount) {
                                                    //数据异常，停止跳绳，作业未完成
                                                    imageResult.setImageResource(R.mipmap.icon_fail);
                                                    textResult.setText("目标未完成");
                                                    layoutResult.setVisibility(View.VISIBLE);
                                                    Log.e(TAG, "数据异常，作业未完成");
                                                    isCompleted = true;
                                                    stopTime();

                                                    SkipDataDTO skipDataDTO = new SkipDataDTO();
                                                    skipDataDTO.setBeginTime(startTime);
                                                    skipDataDTO.setCompleteTime(System.currentTimeMillis());
                                                    skipDataDTO.setSportNum(sportCount);
                                                    skipDataDTO.setSportTime(sportTime);
                                                    uploadWork(skipDataDTO, 0);
                                                    handler.sendEmptyMessageDelayed(0, 3000);
                                                    BleManager.getInstance().write(bleDevice, "*{\"an\":\"sp\",\"nu\":\"" + sportCount + "\",\"t\":\"" + sportTime + "\"}#");
                                                    return;
                                                }
                                                startTime = System.currentTimeMillis();
                                                sportCount = count;
                                                isEffective = true;
                                                imageBleDown.setVisibility(View.GONE);
                                                startButton.setText("停止");
                                                if (studentHomeworkDTO.getType() == 0) {
                                                    //计时计数
                                                    textHint.setText("剩余时间   剩余个数");
                                                } else if (studentHomeworkDTO.getType() == 1) {
                                                    //计时
                                                    textHint.setText("剩余时间");
                                                } else {
                                                    //计数
                                                    textHint.setText("剩余个数");
                                                }
                                                timeTimer = new Timer();
                                                timeTimerTask = new TimerTask() {
                                                    @Override
                                                    public void run() {
                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                sportTime++;
                                                                if (studentHomeworkDTO.getType() == 0) {
                                                                    //计时计数
                                                                    circleProgressbar2.setProgress(circleProgressbar2.getProgress() + 1);
                                                                    textTime.setText(convertSecondsToMinutesSeconds(studentHomeworkDTO.getSportSeconds() - circleProgressbar2.getProgress()));
                                                                    if (circleProgressbar2.getProgress() >= studentHomeworkDTO.getSportSeconds()) {
                                                                        //时间到
                                                                        isCompleted = true;
                                                                        stopTime();
                                                                        if (sportCount < studentHomeworkDTO.getSportCount()) {
                                                                            //未完成
                                                                            imageResult.setImageResource(R.mipmap.icon_fail);
                                                                            textResult.setText("目标未完成");
                                                                            layoutResult.setVisibility(View.VISIBLE);
                                                                            Log.e(TAG, "时间到，作业未完成");

                                                                            SkipDataDTO skipDataDTO = new SkipDataDTO();
                                                                            skipDataDTO.setBeginTime(startTime);
                                                                            skipDataDTO.setCompleteTime(System.currentTimeMillis());
                                                                            skipDataDTO.setSportNum(sportCount);
                                                                            skipDataDTO.setSportTime(sportTime);
                                                                            uploadWork(skipDataDTO, 0);
                                                                        } else {
                                                                            layoutResult.setVisibility(View.VISIBLE);
                                                                            Log.e(TAG, "作业完成，个数：" + sportCount + "，时间：" + sportTime
                                                                                    + "，开始时间：" + startTime + "，结束时间：" + System.currentTimeMillis());

                                                                            SkipDataDTO skipDataDTO = new SkipDataDTO();
                                                                            skipDataDTO.setBeginTime(startTime);
                                                                            skipDataDTO.setCompleteTime(System.currentTimeMillis());
                                                                            skipDataDTO.setSportNum(sportCount);
                                                                            skipDataDTO.setSportTime(studentHomeworkDTO.getSportSeconds());
                                                                            uploadWork(skipDataDTO, 1);
                                                                        }
                                                                        handler.sendEmptyMessageDelayed(0, 3000);
                                                                        BleManager.getInstance().write(bleDevice, "*{\"an\":\"sp\",\"nu\":\"" + sportCount + "\",\"t\":\"" + sportTime + "\"}#");
                                                                    }
                                                                } else if (studentHomeworkDTO.getType() == 1) {
                                                                    //计时
                                                                    if (circleProgressbar1.getProgress() < studentHomeworkDTO.getSportSeconds()) {
                                                                        circleProgressbar1.setProgress(circleProgressbar1.getProgress() + 1);
                                                                        textTime.setText(convertSecondsToMinutesSeconds(studentHomeworkDTO.getSportSeconds() - circleProgressbar1.getProgress()));
                                                                    } else {
                                                                        //时间到，作业完成
                                                                        layoutResult.setVisibility(View.VISIBLE);
                                                                        Log.e(TAG, "作业完成，个数：" + sportCount + "，时间：" + studentHomeworkDTO.getSportSeconds()
                                                                                + "，开始时间：" + startTime + "，结束时间：" + System.currentTimeMillis());
                                                                        isCompleted = true;
                                                                        SkipDataDTO skipDataDTO = new SkipDataDTO();
                                                                        skipDataDTO.setBeginTime(startTime);
                                                                        skipDataDTO.setCompleteTime(System.currentTimeMillis());
                                                                        skipDataDTO.setSportNum(sportCount);
                                                                        skipDataDTO.setSportTime(studentHomeworkDTO.getSportSeconds());
                                                                        uploadWork(skipDataDTO, 1);
                                                                        stopTime();
                                                                        handler.sendEmptyMessageDelayed(0, 3000);
                                                                        BleManager.getInstance().write(bleDevice, "*{\"an\":\"sp\",\"nu\":\"" + sportCount + "\",\"t\":\"" + sportTime + "\"}#");
                                                                    }
                                                                }

                                                            }
                                                        });
                                                    }
                                                };
                                                timeTimer.schedule(timeTimerTask, 0, 1000);
                                            }
                                            if (isEffective) {
                                                if (sportCount != 0 && count < sportCount) {
                                                    //数据异常，停止跳绳
                                                    imageResult.setImageResource(R.mipmap.icon_fail);
                                                    textResult.setText("目标未完成");
                                                    layoutResult.setVisibility(View.VISIBLE);
                                                    Log.e(TAG, "数据异常，作业未完成");
                                                    isCompleted = true;
                                                    stopTime();

                                                    SkipDataDTO skipDataDTO = new SkipDataDTO();
                                                    skipDataDTO.setBeginTime(startTime);
                                                    skipDataDTO.setCompleteTime(System.currentTimeMillis());
                                                    skipDataDTO.setSportNum(sportCount);
                                                    skipDataDTO.setSportTime(sportTime);
                                                    uploadWork(skipDataDTO, 0);
                                                    handler.sendEmptyMessageDelayed(0, 3000);
                                                    BleManager.getInstance().write(bleDevice, "*{\"an\":\"sp\",\"nu\":\"" + sportCount + "\",\"t\":\"" + sportTime + "\"}#");
                                                    return;
                                                }
                                                sportCount = count;
                                                if (studentHomeworkDTO.getType() == 0) {
                                                    //计时计数
                                                    int tvCount = studentHomeworkDTO.getSportCount() - sportCount;
                                                    if (tvCount >= 0) {
                                                        circleProgressbar1.setProgress(sportCount);
                                                        textCount.setText(String.valueOf(tvCount));
                                                    } else {
                                                        circleProgressbar1.setProgress(studentHomeworkDTO.getSportCount()   );
                                                        textCount.setText(String.valueOf(0));
                                                    }
                                                } else if (studentHomeworkDTO.getType() == 2) {
                                                    //计数
                                                    if (sportCount < studentHomeworkDTO.getSportCount()) {
                                                        circleProgressbar1.setProgress(sportCount);
                                                        int tvCount = studentHomeworkDTO.getSportCount() - sportCount;
                                                        if (tvCount >= 0) {
                                                            textCount.setText(String.valueOf(tvCount));
                                                        }
                                                    } else {
                                                        //作业完成
                                                        circleProgressbar1.setProgress(studentHomeworkDTO.getSportCount());
                                                        textCount.setText(String.valueOf(0));
                                                        layoutResult.setVisibility(View.VISIBLE);
                                                        Log.e(TAG, "作业完成，个数：" + studentHomeworkDTO.getSportCount() + "，时间：" + sportTime
                                                                + "，开始时间：" + startTime + "，结束时间：" + System.currentTimeMillis());
                                                        isCompleted = true;
                                                        SkipDataDTO skipDataDTO = new SkipDataDTO();
                                                        skipDataDTO.setBeginTime(startTime);
                                                        skipDataDTO.setCompleteTime(System.currentTimeMillis());
                                                        skipDataDTO.setSportNum(studentHomeworkDTO.getSportCount());
                                                        skipDataDTO.setSportTime(sportTime);
                                                        uploadWork(skipDataDTO, 1);
                                                        stopTime();
                                                        handler.sendEmptyMessageDelayed(0, 3000);
                                                        BleManager.getInstance().write(bleDevice, "*{\"an\":\"sp\",\"nu\":\"" + sportCount + "\",\"t\":\"" + sportTime + "\"}#");
                                                    }
                                                }
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                        }
                    });
            }
        }, 1000);

        startButtonLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("开始".equals(startButton.getText().toString())) {
                    //点击开始
                    imageBleDown.setVisibility(View.GONE);
                    startButton.setText("停止");
                    if (studentHomeworkDTO.getType() == 0) {
                        //计时计数
                        textHint.setText("剩余时间   剩余个数");
                    } else if (studentHomeworkDTO.getType() == 1) {
                        //计时
                        textHint.setText("剩余时间");
                    } else {
                        //计数
                        textHint.setText("剩余个数");
                    }
                    //设置模式参数
                    if (!TextUtils.isEmpty(targetApdu)) {
                        BleManager.getInstance().write(bleDevice, targetApdu);
                    }
                    //设置模式(不能发，发了粉红色的绳有问题)
//                    final String finalTypeApdu = typeApdu;
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            BleManager.getInstance().write(bleDevice, finalTypeApdu);
//                        }
//                    }, 500);
                    //开始跳绳
                    final String finalStartApdu = startApdu;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            BleManager.getInstance().write(bleDevice, finalStartApdu);
                        }
                    }, 500);
                } else {
                    //点击停止
                    if (isEffective) {
                        SkipDataDTO skipDataDTO = new SkipDataDTO();
                        skipDataDTO.setBeginTime(startTime);
                        skipDataDTO.setCompleteTime(System.currentTimeMillis());
                        skipDataDTO.setSportNum(sportCount);
                        skipDataDTO.setSportTime(sportTime);
                        uploadWork(skipDataDTO, 0);

                        //停止跳绳
                        BleManager.getInstance().write(bleDevice, "*{\"an\":\"sp\",\"nu\":\"" + sportCount + "\",\"t\":\"" + sportTime + "\"}#");
                    }
                    finish();
                }
            }
        });

        layoutBleSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageBleDown.getVisibility() == View.VISIBLE) {
                    Intent intent = new Intent(WorkActivity.this, ScanBleActivity.class);
                    intent.putExtra("data", studentHomeworkDTO);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        stopTime();
        if (powerTimer != null) {
            powerTimer.cancel();
        }
        if (powerTimerTask != null) {
            powerTimerTask.cancel();
        }
        powerTimer = null;
        powerTimerTask = null;
        handler.removeMessages(0);
        BleManager.getInstance().stopNotify(bleDevice, BleManager.getInstance().NOTIFY_SERVICE_UUID, BleManager.getInstance().NOTIFY_UUID);
        unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }

    private void stopTime() {
        if (timeTimer != null) {
            timeTimer.cancel();
        }
        if (timeTimerTask != null) {
            timeTimerTask.cancel();
        }
        timeTimer = null;
        timeTimerTask = null;
    }

    @SuppressLint("DefaultLocale")
    private String convertSecondsToMinutesSeconds(int seconds) {
        int minutes = seconds / 60; // 计算分钟数
        int remainingSeconds = seconds % 60; // 计算剩余的秒数
        String secondsStr = String.format("%02d", remainingSeconds);
        String minutesStr = String.format("%02d", minutes);
        return minutesStr + ":" + secondsStr;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            AppApplication.getInstance().exit();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("DIS_CONNECT_BLE".equals(action)) {
                textBle.setText("蓝牙未连接");
                textPower.setText("");
                Toast.makeText(WorkActivity.this, "跳绳未连接", Toast.LENGTH_SHORT).show();

                if (startTime != 0) {
                    final SkipDataDTO skipDataDTO = new SkipDataDTO();
                    skipDataDTO.setBeginTime(startTime);
                    skipDataDTO.setCompleteTime(System.currentTimeMillis());
                    skipDataDTO.setSportNum(sportCount);
                    skipDataDTO.setSportTime(sportTime);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            SkipWorkServiceImpl.upSkipHomework(studentHomeworkDTO.getHomeworkRedirectUrl(), skipDataDTO);
                            stopTime();
                        }
                    }).start();
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 3000);
            }
        }
    };

    /**
     * 上报作业完成情况
     * @param dataDTO
     * @param page 1完成，0未完成
     */
    private void uploadWork(final SkipDataDTO dataDTO, final int page) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SkipWorkServiceImpl.upSkipHomework(studentHomeworkDTO.getHomeworkRedirectUrl(), dataDTO);
                Intent intent = new Intent("REFRESH_LIST");
                intent.putExtra("page", page);
                sendBroadcast(intent);
                stopTime();
            }
        }).start();
    }

    /**
     * 上报历史数据
     * @param dataDTOS
     */
    private void uploadHistoryWork(final List<SkipDataDTO> dataDTOS) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SkipWorkServiceImpl.upHistorySkip(AppApplication.getInstance().historyUrl, dataDTOS);
            }
        }).start();
    }
}